package com.huitong.common.redis.config;

import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.huitong.common.redis.hander.KeyPrefixHandler;
import com.huitong.common.redis.manager.CustomCacheManager;
import com.huitong.common.redis.properties.RedissonCustomProperties;
import lombok.extern.slf4j.Slf4j;
import org.redisson.client.codec.StringCodec;
import org.redisson.codec.CompositeCodec;
import org.redisson.codec.TypedJsonJacksonCodec;
import org.redisson.spring.starter.RedissonAutoConfigurationCustomizer;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;

/**
 * Redisson配置
 *
 * @author fromdrowning
 * @date 2024/3/16 20:35
 */
@Slf4j
@AutoConfiguration
@EnableCaching
@EnableConfigurationProperties(RedissonCustomProperties.class)
public class RedisConfiguration {

    /**
     * 自定义缓存管理器 整合SpringCache
     *
     * @return 自定义缓存管理器
     */
    @Bean
    public CacheManager cacheManagerCustomizer() {
        return new CustomCacheManager();
    }

    /**
     * Redisson配置
     *
     * @param properties   Redisson自定义配置
     * @param objectMapper Jackson序列化格式
     * @return 配置后的Redisson
     */
    @Bean
    public RedissonAutoConfigurationCustomizer redissonCustomizer(RedissonCustomProperties properties, ObjectMapper objectMapper) {
        return config -> {
            ObjectMapper om = objectMapper.copy();
            om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY)
                // 指定序列化输入的类型 类必须是非final修饰的 序列化时将对象全类名一起保存下来
                .activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);

            TypedJsonJacksonCodec jsonCodec = new TypedJsonJacksonCodec(Object.class, om);

            config.setThreads(properties.getThreads())
                .setNettyThreads(properties.getNettyThreads())
                // 缓存Lua脚本 减少网络传输
                .setUseScriptCache(true)
                // 组合序列化 key使用String 内容使用通用json格式
                .setCodec(new CompositeCodec(StringCodec.INSTANCE, jsonCodec, jsonCodec));

            // 单机配置
            RedissonCustomProperties.SingleServer singleServer = properties.getSingleServer();
            if (ObjectUtil.isNotNull(singleServer)) {
                config.useSingleServer()
                    // 设置redis key前缀
                    .setNameMapper(new KeyPrefixHandler(properties.getKeyPrefix()))
                    .setTimeout(singleServer.getTimeout())
                    .setClientName(singleServer.getClientName())
                    .setIdleConnectionTimeout(singleServer.getIdleConnectionTimeout())
                    .setSubscriptionConnectionPoolSize(singleServer.getSubscriptionConnectionPoolSize())
                    .setConnectionMinimumIdleSize(singleServer.getConnectionMinimumIdleSize())
                    .setConnectionPoolSize(singleServer.getConnectionPoolSize());
            }

            // 集群配置
            RedissonCustomProperties.ClusterServers clusterServers = properties.getClusterServers();
            if (ObjectUtil.isNotNull(clusterServers)) {
                config.useClusterServers()
                    // 设置redis key前缀
                    .setNameMapper(new KeyPrefixHandler(properties.getKeyPrefix()))
                    .setTimeout(clusterServers.getTimeout())
                    .setClientName(clusterServers.getClientName())
                    .setIdleConnectionTimeout(clusterServers.getIdleConnectionTimeout())
                    .setSubscriptionConnectionPoolSize(clusterServers.getSubscriptionConnectionPoolSize())
                    .setMasterConnectionMinimumIdleSize(clusterServers.getMasterConnectionMinimumIdleSize())
                    .setMasterConnectionPoolSize(clusterServers.getMasterConnectionPoolSize())
                    .setSlaveConnectionMinimumIdleSize(clusterServers.getSlaveConnectionMinimumIdleSize())
                    .setSlaveConnectionPoolSize(clusterServers.getSlaveConnectionPoolSize())
                    .setReadMode(clusterServers.getReadMode())
                    .setSubscriptionMode(clusterServers.getSubscriptionMode());
            }

            log.info("初始化Redis配置完成");
        };
    }
}
